<script setup lang="ts">
import GiftAPI from "@/api/gift";
import { ref, reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";

const title = ref<string>("");
const handleQuery = () => {
  loadData(1);
  title.value = "";
};

// 初始表单数据
const initialFormData = {
  name: "",
  description: "",
  point: 0,
  imageUrl: "",
};

// 修改
const handleOpenDialog = async (id?: number) => {
  if (id) {
    formData.value = await GiftAPI.get(id);
    // 初始化图片文件列表
    if (formData.value.imageUrl) {
      imageFileList.value = [{ name: "图片", url: formData.value.imageUrl }];
    }
    dialog.value.visible = true;
  } else {
    formData.value = { ...initialFormData };
    imageFileList.value = [];
    dialog.value.visible = true;
  }
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    GiftAPI.delete(id).then(() => {
      ElMessage.success("删除成功");
      loadData(1);
    });
  });
};

const loading = ref(false);
const pageData = ref<any>();
const total = ref<number>(0);
const pageNum = ref(1);
const pageSize = ref(10);

const loadDataPage = async (
  name: string,
  pageNum: number,
  pageSize: number
) => {
  return await GiftAPI.getPage(name, pageSize, pageNum);
};

const loadData = (num: number) => {
  pageNum.value = num;
  loadDataPage(title.value, num, pageSize.value).then((data) => {
    total.value = data.total;
    pageData.value = data.records;
  });
};

loadDataPage(title.value, pageNum.value, pageSize.value).then((data) => {
  total.value = data.total;
  pageData.value = data.records;
});

// 新增/修改逻辑
const giftFormRef = ref();
const handleSubmit = () => {
  if (giftFormRef.value) {
    giftFormRef.value.validate((valid: boolean) => {
      if (valid) {
        GiftAPI.save(formData.value).then((data) => {
          if (formData.value.id) {
            ElMessage.success("修改成功");
          } else {
            ElMessage.success("新增成功");
          }
          handleCloseDialog();
          loadData(1);
        });
      }
    });
  }
};

const handleCloseDialog = () => {
  dialog.value.visible = false;
};

const formData = ref<any>({
  ...initialFormData,
});
const drawerSize = ref<number>(500);
const dialog = ref({
  visible: false,
  title: "礼物",
});

const rules = reactive({
  name: [{ required: true, message: "礼物名称不能为空", trigger: "blur" }],
  point: [{ required: true, message: "积分不能为空", trigger: "change" }],
  imageUrl: [{ required: true, message: "请上传礼物图片", trigger: "blur" }],
});

// 图片上传相关
const imageFileList = ref<any[]>([]);

// 上传前的验证
const beforeImageUpload = (file: File) => {
  const isImage = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
  }

  return isImage && isLt2M;
};

// 上传成功处理
const handleImageSuccess = (response: any) => {
  let url = "";

  if (typeof response === "string") {
    url = response;
  } else if (response.url) {
    url = response.url;
  } else if (response.data?.url) {
    url = response.data.url;
  }

  if (url) {
    formData.value.imageUrl = url;
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("图片上传失败，请重试");
  }
};

// 删除图片处理
const handleImageRemove = () => {
  formData.value.imageUrl = "";
};
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="title"
            placeholder="礼物名称"
            style="width: 240px"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-card shadow="hover" class="data-table">
        <div class="data-table__toolbar">
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="pageData"
          border
          stripe
          highlight-current-row
          class="data-table__content"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="礼物名称" prop="name" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="所需积分" prop="point" />
          <el-table-column label="图片" prop="imageUrl">
            <template #default="scope">
              <el-image
                v-if="scope.row.imageUrl"
                :src="'/api' + scope.row.imageUrl"
                :preview-src-list="['/api' + scope.row.imageUrl]"
                style="width: 60px; height: 60px; border-radius: 4px;"
                fit="cover"
                preview-teleported
                hide-on-click-modal
              />
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleOpenDialog(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                icon="delete"
                link
                size="small"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="data-el-pagination">
          <el-pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="pageNum"
            v-model:limit="pageSize"
            @pagination="loadData"
          />
        </div>
      </el-card>
    </div>

    <!-- 礼物表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form
        ref="giftFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="礼物名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入礼物名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="所需积分" prop="point">
          <el-input v-model="formData.point" placeholder="请输入所需积分" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            action="/api/api/file/upload"
            :limit="1"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
            :on-remove="handleImageRemove"
            :file-list="imageFileList"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.upload-preview {
  margin-top: 10px;
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  display: block;
}

.preview-container {
  margin-top: 15px;
}

.preview-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

:deep(.el-upload-list__item) {
  transition: none !important;
}
</style>
